<template>
    <textarea ref="query"></textarea>
</template>
<script setup>
import { CodeMirror } from '../../libs/CodeMirror'
import { nextTick, ref ,watch} from 'vue'
const query = ref(null);
const props = defineProps(['ContentData','activeKey']);

var queryArray = {
    data: [],
    Schema: {},
};
const renderAnnotation = item => ' // ' + item.annotate + ' (' + item.type + ') ' + (item.checked ? '必填' : '') + '\n';
const beautify = (source) => {
    function looks_like_html(source) {
        var trimmed = source.replace(/^[ \t\n\r]+/, '');
        return trimmed && (trimmed.substring(0, 1) === '<');
    };
    var output,
        opts = {
            // brace_style : "expand"
        };
    opts.indent_char = ' ';
    opts.preserve_newlines = "-1";
    if (looks_like_html(source)) {
        output = html_beautify(source, opts);
    } else {
        output = js_beautify(source, opts);
    };
    return output;
};
var Textarea = null;
nextTick(() => {
    Textarea = CodeMirror.fromTextArea(query.value, {
        mode: 'text/javascript',
        indentWithTabs: true,
        smartIndent: false,
        lineNumbers: true,
        lineWrapping: true,
        foldGutter: true,
        matchBrackets: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
        theme: 'mdn-like',
    });
    Textarea.on('beforeChange', (instance, changeObj) => {
        if (changeObj.origin == '+input' && (changeObj.text == '\'' || changeObj.text == '\"')) {
            var _str = Textarea.getSelection();
            if (_str.toString().length > 0) {
                Textarea.replaceSelection(_str + _str + changeObj.text);
            };
        };
    });

    props.ContentData.item.query.forEach(ele => {
        var _data = {};
        _data.key = ele.name;
        _data.type = ele.schema.type;
        _data.annotate = ele.description || '';
        _data.checked = !ele.nullable;
        queryArray.data.push(_data);
        queryArray.Schema[ele.name] = ele.schema;
    });
    var data = queryArray.data;
    var _String = '{'
    for (let i = 0; i < data.length; i++) {
        var item = data[i];
        if (item.type == 'object') {
            _String += (item.key + ': {},' + renderAnnotation(item));
        } else {
            _String += ((item.key ? item.key : '\'\'') + ':' + '\'\',' + renderAnnotation(item));
        }
    };
    _String += '}'
    var str = beautify(_String);
    Textarea.setValue(str);
})

watch(() => props.activeKey, (val) => {
    if (val == 'query') {
        setTimeout(() => {
            Textarea.refresh();
        }, 10)
    }
});

const getValue = () => Textarea.getValue();

defineExpose({
    getValue
})

</script>
<style lang="less" scoped>

</style>